package eshore.cn.it.solrhandler;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;

import eshore.cn.it.solrhandler.config.SolrApp;


public class SolrUtils {
	@Autowired
	private SolrApp solrApp;
	
	public SolrApp getSolrApp() {
		return solrApp;
	}
	public void setSolrApp(SolrApp solrApp) {
		this.solrApp = solrApp;
	}

	
	
	private  int maxDocs = 10000;
	
	
 	public  void search(String word) {
		
		SolrQuery params = new SolrQuery();
		
		//下面设置查询的参数
		// 查询关键词，*:*代表所有属性、所有值，即所有index
		params.set("q", "content:" + word);
		//params.set("q", "nickname:chm*");// 查询nickname是已chm开头的数据
	
		//分页，start=0就是从0开始，，rows=5当前返回5条记录，第二页就是变化start这个值为5就可以了。
		params.set("start", 0);
		params.set("rows", 5);
	
		params.setHighlight(true).setHighlightSnippets(1); //set other params as needed
		params.setParam("hl.fl", "content");

		// 按nickname排序，asc升序 desc降序
		// params.set("sort", "nickname asc");
	
		try {
			//执行查询
			QueryResponse rsp = getSolrApp().getSolrClient().query(params);
			
			//获取查询结果并且打印
			Iterator<SolrDocument> iter = rsp.getResults().iterator();

		    while (iter.hasNext()) {
		      SolrDocument resultDoc = iter.next();

		      String id = (String) resultDoc.getFieldValue("id"); //id is the uniqueKey field

		      if (rsp.getHighlighting().get(id) != null) {
		          List<String> highlightSnippets = rsp.getHighlighting().get(id).get("content");
		          System.out.println(highlightSnippets);
		      }
		    }
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	public  void deleteIndex(List<String> ids) {
		try {
			if (ids == null)
				getSolrApp().getSolrClient().deleteByQuery("*:*");
			else {
				getSolrApp().getSolrClient().deleteById(ids);
			}
			getSolrApp().getSolrClient().commit();
		} catch (SolrServerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void addDocument() {
		String path = "data/81万词库.txt";
		
		FileReader reader = null;
		try {
			reader = new FileReader(new File(path));
			List<String> content = IOUtils.readLines(reader);
			
			long start = System.currentTimeMillis();
			int mark = 0;
			List<SolrInputDocument> sids = new ArrayList<SolrInputDocument>();
			for (int i = 0; i < content.size(); i++) {
				SolrInputDocument doc1 = new SolrInputDocument();
				doc1.addField("id", "id" + i);
				doc1.addField("_jiebacontent_", content.get(i));
				sids.add(doc1);
				mark++;
				if (mark == maxDocs) {
					getSolrApp().getSolrClient().add(sids);
					getSolrApp().getSolrClient().commit();
					sids.clear();
					mark = 0;
				}
			}
			long end = System.currentTimeMillis();
			System.out.println("加入81万词到  Solr 建立索引所花时间为：" + (end - start) + "ms");
		} catch (SolrServerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(reader);
		}
	}

	public static void main(String[] args) {
		SolrUtils su = new SolrUtils();
		su.deleteIndex(null);
		//su.addDocument();//实际应用过程中可以根据自身需要传参
		
		//su.search("中国");
		//su.search("美女");
		//su.testSearch();
	}
	
	public static void testSearch() {
		SolrUtils su = new SolrUtils();
		su.deleteIndex(null);
		long start = System.currentTimeMillis();
		String testFile = "data/testSearchWords";
		try {
			List<String> words = FileUtils.readLines(new File(testFile));
			for (String word : words) {
				String[] ws = word.split("-");
				su.search(ws[0]);
				su.search(ws[1]);
			}
			long end = System.currentTimeMillis();
			System.out.println("搜索100个词语所花时间为：" + (end - start) + "ms");
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}
